package com.OrderingSystem.controller.common;

import com.OrderingSystem.utils.Result;
import com.alibaba.fastjson.JSON;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;


@RestController
@RequestMapping("/files")
@Api(tags = "文件上传接口")
public class FileController {

    // 七牛云相关配置
    @Value("${qiniu.accessKey}")
    private String accessKey;

    @Value("${qiniu.secretKey}")
    private String secretKey;

    @Value("${qiniu.bucket}")
    private String bucket;

    @Value("${qiniu.domain}")
    private String domain;

    @PostMapping("/upload")
    @ApiOperation("文件上传")
    public Result upload(MultipartFile file) throws IOException {

        // 构造一个带指定 Region 对象的配置类
        Configuration cfg = new Configuration(Region.region0()); // 华东地区
        // ...其他参数参考类注释
        UploadManager uploadManager = new UploadManager(cfg);

        // 获取原始文件名
        String originalFilename = file.getOriginalFilename();
        // 获取文件扩展名
        String ext = "";
        if (originalFilename != null && originalFilename.contains(".")) {
            ext = originalFilename.substring(originalFilename.lastIndexOf("."));
        }
        // 用 UUID 生成文件名
        String fileName = UUID.randomUUID().toString() + ext;


        Auth auth = Auth.create(accessKey, secretKey);
        String upToken = auth.uploadToken(bucket);

        try {
            Response response = uploadManager.put(file.getBytes(), fileName, upToken);
            // 解析上传成功的结果
            DefaultPutRet putRet = JSON.parseObject(response.bodyString(), DefaultPutRet.class);

            // 返回文件的访问URL
            String url = domain + "/" + putRet.key;
            return Result.success(url);
        } catch (Exception ex) {
            ex.printStackTrace();
            return Result.error("文件上传失败: " + ex.getMessage());
        }
    }

}